""" command_manager.py """
from __future__ import with_statement
import sys, os, time, urllib, httplib, threading, simplejson as json
import mac

HTTP_SERVER = 'roqueislandmonitor.appspot.com'
BASE_URL = 'http://'+HTTP_SERVER
# COMMAND_URL = 'http://127.0.0.1/command.json'
COMMAND_URL = BASE_URL + '/outstanding'
COMMAND_RESULTS = '/var/www/command-results.txt'

MAC_ADDR = mac.getMacAddress()

theCommand = '';

class MyThread ( threading.Thread ):

   def run ( self ):

      global theCommand
      print 'starting: ', theCommand
      status = os.system(theCommand)
      print 'os.system(): ', status 

def get_json_url(url):
    try:
        f = urllib.urlopen(url)
        data = f.read()
        f.close()
        # print data
        obj = json.loads(data)
        # obj['good'] = True
    except:
        print sys.exc_info()[0]
        obj = []
        # obj = {'good':False}
    return obj

def post(data):
    data['timestamp'] = time.ctime()
    data['mac'] = MAC_ADDR
    json_data = json.dumps(data)
    # print json_data
    params = urllib.urlencode({'content': json_data})
    conn = httplib.HTTPConnection(HTTP_SERVER)
    headers = {"Content-type": "application/x-www-form-urlencoded",
               "Accept": "text/plain"}
    conn.request('POST', '/response', params, headers)
    resp = conn.getresponse()
    if resp.status != 200:
        #raise Exception(resp.reason)
        print resp.status
    resp.read()
    conn.close()

def do_command(command_obj):
    command = command_obj['shell']
    print command
    if command == '':
        return
    p = os.popen('timeout 60 '+command)
    result = p.read()
    p.close()
    # print result
    post({'key':command_obj['key'],'command':command,'result':result})
    with open(COMMAND_RESULTS, 'w') as f: 
        f.write(result)

def do_shutdown(command_obj):
    post({'key':command_obj['key'],'command':'shutdown','result':'shutting down'})
    os.system('shutdown now')

def do_upload(command_obj):
    path = command_obj['path']
    try:
        with open(path,'w') as f:
            f.write(command_obj['file'] if command_obj['type'] == 'file' else command_obj['text'])
        post({'key':command_obj['key'],'result':'written'})
    except:
        post({'key':command_obj['key'],'result':'not written'})

def do_launch(command_obj):
    global theCommand
    theCommand = command_obj['shell']
    MyThread().start()
    post({'key':command_obj['key'],'command':theCommand,'result':'launched'})
    
def handle_commands(urldata):
    for command_obj in urldata:
        type = command_obj['type']
        if type == 'shell':
            do_command(command_obj)
        elif type == 'file':
            do_upload(command_obj)
        elif type == 'text':
            do_upload(command_obj)
        elif type == 'shutdown':
            do_shutdown(command_obj)
        elif type == 'launch':
            do_launch(command_obj)

def main():
    run = True
    while run:
        # print('start')
        urldata = get_json_url(COMMAND_URL+'?mac='+MAC_ADDR)
        handle_commands(urldata)
        # run = False
        time.sleep(5)

if __name__ == '__main__':
    main()

